<script>
import { handleMoney, showToast } from "@/utils"
import quanIcon from "./assets/quan.png"
import rightIcon from "./assets/right.png"
import closeIcon from "../../static/close_line.png"
import http from "@/utils/request"
import request from "@/utils/request"

export default {
  name: "index",
  methods: {
    handleMoney,
    currentSelectItemChange(val) {
      //优惠券不可用
      if (val.disabled) return
      //选中不同的优惠券
      if (!this.currentSelectItem || val.userCouponId !== this.currentSelectItem.userCouponId) {
        this.changeCurrentItem(val)
      } else {
        //取消选中
        this.changeCurrentItem(null)
      }
      // this.$refs.popup.close()
    },
    changeCurrentItem(val) {
      this.currentSelectItem = val
      //计算优惠后的价格
      if (this.currentSelectItem) {
        let result = this.calculateDiscountPrice(this.originPrice)
        this.$emit("update:couponDiscount", result)
        this.$emit("update:userCouponId", this.currentSelectItem.userCouponId)
        this.$emit("change", val)
      } else {
        this.$emit("update:couponDiscount", 0)
        this.$emit("update:userCouponId", "")
        this.$emit("change", null)
      }
    },
    //计算优惠券优惠后的减免价格（供父组件调用）
    calculateDiscountPrice(originPrice) {
      let result = 0
      //价格减免策略
      if (this.currentSelectItem.priceStrategy === "0") {
        result = this.currentSelectItem.price
        //折扣策略
      } else if (this.currentSelectItem.priceStrategy === "1") {
        result = originPrice - originPrice * this.currentSelectItem.discountRate
        //满减策略
      } else if (this.currentSelectItem.priceStrategy === "2") {
        //判断是否达到满减条件
        if (originPrice >= this.currentSelectItem.fullYuan && this.currentSelectItem.fullYuan !== 0) {
          result = this.currentSelectItem.price
        }
      }
      return result
    },
    //获取优惠券列表
    getCouponList() {
      uni.showLoading({
        title: "加载中...",
      })
      this.loading = true
      http({
        url: "userCoupon/page",
        method: "post",
        data: {
          current: 1,
          size: -1,
          couponTypeList: this.couponTypeList,
        },
      })
        .then((res) => {
          if (res.records.length === 0) {
            //取消选中
            this.changeCurrentItem(null)
          }
          this.couponList = res.records
          this.excludeFullYuanCoupon() //处理满减策略
          //默认选中第一个
          let selectedItem = this.couponList.find((item) => !item.disabled)
          selectedItem && this.changeCurrentItem(selectedItem)
        })
        .catch((err) => {
          console.log(err, "err")
          showToast.default(err)
        })
        .finally(() => {
          this.loading = false
          uni.hideLoading()
        })
    },
    //排除满减策略里面由于达不到满减条件导致无法使用的优惠券
    excludeFullYuanCoupon() {
      if (this.couponList.length === 0) return
      for (let couponListElement of this.couponList) {
        if (couponListElement.priceStrategy === "2" && this.originPrice < couponListElement.fullYuan) {
          this.$set(couponListElement, "disabled", true)
        }
      }
    },
    //提交优惠码兑换优惠券
    submitExchangeCoupons() {
			if (!this.couponCode) {
				showToast.default("请输入优惠码")
				return
			}
      request({
        url: "userCoupon/getUserCouponId",
        data: {
					couponCode: this.couponCode, //优惠码
				},
        showLoading: true,
        errorHandle: true,
      }).then((data) => {
        showToast.default("兑换成功，已自动选中兑换的优惠券")
        //兑换成功后将优惠券添加到列表的第一位
        this.couponList.unshift(data)
        //默认选中刚插入的兑换码
        this.changeCurrentItem(data)
				this.couponCode = ""
      })
    },
  },
  data() {
    return {
      quanIcon,
      rightIcon,
      closeIcon,
      couponList: [], // 优惠券列表
      currentSelectItem: null, // 当前选中的优惠券
      inputFocus: false, //优惠码输入框是否处于聚焦状态
			couponCode: "", //优惠码
    }
  },
  props: {
    couponTypeList: Array, // 优惠券类型列表
    originPrice: Number, // 原价
    couponDiscount: Number, // 使用了优惠券后减免的价格
    noCoupon: Boolean, // 是否没有优惠券，用于父组件进行条件渲染
    userCouponId: String, // 优惠券id
  },
  watch: {
    couponList(val) {
      if (!val || val.length === 0) {
        this.$emit("update:noCoupon", true)
      }
    },
  },
  created() {
    this.getCouponList()
  },
  emits: ["update:couponDiscount", "update:noCoupon", "change", "update:userCouponId"],
}
</script>

<template>
  <view class="component">
    <!--		当前选择的优惠券banner-->
    <view class="coupon-banner">
      <view class="left block">
        <image class="icon" :src="quanIcon"></image>
        <view class="text">优惠券</view>
      </view>
      <view class="right block" @click="$refs.popup.open()">
        <view class="coupon-name">{{ currentSelectItem ? currentSelectItem.couponName : "未选择" }} </view>
        <!--			减免价格-->
        <template v-if="currentSelectItem">
          <!--				价格减免策略-->
          <view class="discount-the-price" v-if="currentSelectItem.priceStrategy === '0'"
            >-￥{{ handleMoney(currentSelectItem.price) }}
          </view>
          <!--				折扣策略-->
          <view class="discount-the-price" v-else-if="currentSelectItem.priceStrategy === '1'"
            >{{ currentSelectItem.discountRate * 10 }} 折
          </view>
          <!--				满减-->
          <view class="discount-the-price" v-else-if="currentSelectItem.priceStrategy === '2'"
            >满 {{ handleMoney(currentSelectItem.fullYuan) }} 减 {{ handleMoney(currentSelectItem.price) }}
          </view>
        </template>
        <image class="right-arrow" :src="rightIcon"></image>
      </view>
    </view>
    <!--		选择优惠券弹框-->
    <uni-popup ref="popup" type="bottom">
      <view class="coupon-list">
        <view class="header">
          <view></view>
          <view class="title">选择优惠券</view>
          <image class="close-btn" :src="closeIcon" @click="$refs.popup.close()"></image>
        </view>
        <view class="coupon-wrapper">
          <!--						优惠码兑换优惠券输入框-->
          <view class="promotion-code">
            <view class="label">优惠码</view>
            <view class="promotion-code-input">
              <input
                placeholder="用于兑换优惠券"
                class="input"
                @focus="inputFocus = true"
                @blur="inputFocus = false"
                :adjust-position="false"
								v-model="couponCode"
              />
            </view>
            <view class="confirm-btn" @click="submitExchangeCoupons">兑换</view>
          </view>
          <!--					兑换码列表-->
          <radio-group>
            <view class="coupon-item-wrapper" v-for="item in couponList" :key="item.userCouponId">
              <view class="coupon-item" @click="currentSelectItemChange(item)">
                <view class="left" v-if="!item.disabled">
                  <radio
                    :value="item.userCouponId"
                    :checked="currentSelectItem && item.userCouponId === currentSelectItem.userCouponId"
                  ></radio>
                </view>
                <!--								优惠券不可用-->
                <view class="placeholder" v-else>不可用</view>
                <view class="right">
                  <view class="left">
                    <!--										优惠券名称-->
                    <view class="coupon-name">{{ item.couponName }}</view>
                    <!--										说明-->
                    <view class="info" v-if="item.intro">{{ item.intro }}</view>
                    <!--										优惠券有效期-->
                    <view class="info">有效期：{{ item.expireTime }} </view>
                  </view>
                  <view class="right">
                    <!--									价格减免策略-->
                    <view class="price" v-if="item.priceStrategy === '0'">减￥{{ handleMoney(item.price) }} </view>
                    <!--										打折-->
                    <view class="price" v-else-if="item.priceStrategy === '1'">{{ item.discountRate * 10 }} 折 </view>
                    <!--										满减-->
                    <view class="price" v-else-if="item.priceStrategy === '2'"
                      >满 {{ handleMoney(item.fullYuan) }} 减 {{ handleMoney(item.price) }}
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </radio-group>
					<!--			优惠码输入框占位，为了防止虚拟键盘遮挡输入框-->
					<view style="height: 40vh" v-show="inputFocus"></view>
				</view>
      </view>
    </uni-popup>
  </view>
</template>

<style scoped lang="scss">
.coupon-banner {
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  height: 80rpx;

  .block {
    display: flex;
    align-items: center;
  }

  > .left {
    .icon {
      width: 35rpx;
      height: 35rpx;
    }

    .text {
      color: #333;
      font-size: 28rpx;
      font-weight: 500;
      margin-left: 10rpx;
    }
  }

  > .right {
    flex: 1;
    display: flex;
    justify-content: flex-end;
    margin-left: 30rpx;

    .coupon-name {
      color: #333;
      font-size: 28rpx;
      font-weight: 500;
    }

    .discount-the-price {
      color: red;
      font-size: 26rpx;
      font-weight: 500;
      margin-left: 20rpx;
    }

    .right-arrow {
      width: 12rpx;
      height: 20rpx;
      margin-left: 20rpx;
    }
  }
}
.coupon-list {
  background-color: #fff;
  padding: 30rpx;
  border-radius: 50rpx 50rpx 0 0;
  max-height: 70vh;
  display: flex;
  flex-direction: column;

  > .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;

    > .title {
      font-size: 32rpx;
      font-weight: 500;
    }

    .close-btn {
      width: 50rpx;
      height: 50rpx;
    }
  }

  .coupon-wrapper {
    height: 0;
    flex: 1;
    overflow: auto;

    .promotion-code {
      display: flex;
      align-items: center;
      background: white;
      padding: 20rpx 0;

      &:not(:last-child) {
        border-bottom: 2rpx solid #eee;
      }

      .label {
        margin-right: 20rpx;
        font-size: 28rpx;
      }

      .promotion-code-input {
        background: var(--gray-background-color);
        padding: 20rpx 30rpx;
        width: 0;
        flex: 1;
        border-radius: 20rpx;

        .input {
          width: 100%;
          font-size: 28rpx;
        }
      }

      .confirm-btn {
        background: var(--theme-color);
				color: var(--text-color-white);
        padding: 0 30rpx;
        height: 60rpx;
        line-height: 60rpx;
        border-radius: 30rpx;
        margin-left: 10rpx;
      }
    }

    .coupon-item-wrapper {
      padding: 20rpx 0;

      &:not(:last-child) {
        border-bottom: 2rpx solid #eee;
      }

      .coupon-item {
        display: flex;
        align-items: center;

        > .placeholder {
          width: 80rpx;
          height: 50rpx;
          font-size: 26rpx;
        }

        > .right {
          background: #e86b71;
          border-radius: 10rpx;
          padding: 20rpx 20rpx;
          margin-left: 20rpx;
          width: 0;
          flex: 1;
          display: flex;
          justify-content: space-between;
          align-items: center;

          &.disable {
            background: #8d8d8d;
          }

          > .left {
            .coupon-name {
              color: #fff;
              font-size: 32rpx;
              font-weight: 500;
            }

            .info {
              color: #fff;
              font-size: 24rpx;
              font-weight: 500;
              margin-top: 10rpx;
            }
          }

          > .right {
            .price {
              color: #fff;
              font-size: 32rpx;
              font-weight: 500;
            }
          }
        }
      }
    }
  }
}
</style>
